package com.gamota.mobi;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.Log;

import com.gamota.mobi.util.CommonUtils;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
//@ReportsCrashes(formKey = "dExlWVJNZGd1RW51MUt5WmtmUElrR1E6MQ")
public class UILApplication extends Application {

	public static final String TAG = "UILApplication";
	private int listDetailId = -1;
	private Configuration config;
	public int getListDetailId() {
		return listDetailId;
	}

	public void setListDetailId(int listDetailId) {
		this.listDetailId = listDetailId;
	}
	
	private Thread.UncaughtExceptionHandler androidDefaultUEH;
	private Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
		private String LINE_SEPARATOR="\n";
		public void uncaughtException(Thread thread, Throwable exception) {
			StringWriter stackTrace = new StringWriter();
			exception.printStackTrace(new PrintWriter(stackTrace));
			StringBuilder errorReport = new StringBuilder();
			errorReport.append("************ CAUSE OF ERROR ************\n\n");
			errorReport.append(stackTrace.toString());
			errorReport.append("\n************ DEVICE INFORMATION ***********\n");
			errorReport.append("Brand: ");
			errorReport.append(Build.BRAND);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Device: ");
			errorReport.append(Build.DEVICE);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Model: ");
			errorReport.append(Build.MODEL);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Id: ");
			errorReport.append(Build.ID);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Product: ");
			errorReport.append(Build.PRODUCT);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("\n************ FIRMWARE ************\n");
			errorReport.append("SDK: ");
			errorReport.append(Build.VERSION.SDK);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Release: ");
			errorReport.append(Build.VERSION.RELEASE);
			errorReport.append(LINE_SEPARATOR);
			errorReport.append("Incremental: ");
			errorReport.append(Build.VERSION.INCREMENTAL);
			errorReport.append(LINE_SEPARATOR);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
			Date now = new Date();
			String date = simpleDateFormat.format(now);
			CommonUtils.writetoFile(date+"\n"+errorReport, "crashes.log");
			Intent a=new Intent();
			a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Intent intent = new Intent(getApplicationContext(), DisplayCrashDialog.class);
			intent.putExtra("error", errorReport.toString());
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(10);
			androidDefaultUEH.uncaughtException(thread, exception);
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
//		androidDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
//		Thread.setDefaultUncaughtExceptionHandler(handler);
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		int auto_language=sharedPref.getInt(SettingsActivity.KEY_SET_LANGUAGE, -1);
		Locale locale;
		if(auto_language==0)
		{
			locale = new Locale("vi");  
		}else if(auto_language==1)
		{
			locale = new Locale("en");
		}else
		{
			String _locale=getResources().getString(R.string.default_locale);
			locale = new Locale(_locale);
			SharedPreferences.Editor editor=sharedPref.edit();
			editor.putInt(SettingsActivity.KEY_SET_LANGUAGE, _locale.equals("vi")?0:1);
			editor.commit();
		}
		Log.e("locale","locale: "+locale.getCountry());
		config = new Configuration();  
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
		instance = this;
		// The following line triggers the initialization of ACRA
//        ACRA.init(this);
	}

	public Configuration getConfig() {
		return config;
	}

	public void setConfig(Configuration config) {
		this.config = config;
		getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor=sharedPref.edit();
		editor.putInt(SettingsActivity.KEY_SET_LANGUAGE, config.locale.getLanguage().equals("vi")?0:1);
		editor.commit();
	}

	public enum PlayerClass {
		TRACK;
	}

	/**
	 * Tag used for DDMS logging
	 */

	/**
	 * Singleton pattern
	 */
	private static UILApplication instance;

	/**
	 * Image cache, one for all activities and orientations
	 */

	/**
	 * Web request cache, one for all activities and orientations
	 */

	/**
	 * Service player engine
	 */

	public static UILApplication getInstance() {
		return instance;
	}

	/**
	 * Access to global image cache across Activity instances
	 * 
	 * @return
	 */
	public String getVersion() {
		String version = "0.0.0";

		PackageManager packageManager = getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(
					getPackageName(), 0);
			version = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return version;
	}


	
	public boolean isLoadAllImgs() {
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		return sharedPref.getBoolean(SettingsActivity.ALLOW_LOAD_ALL_IMGs, true);
	}

	public void setLoadAllImgs(boolean loadAllImgs) {
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		sharedPref.edit().putBoolean(SettingsActivity.ALLOW_LOAD_ALL_IMGs,loadAllImgs);
	}

	public int task_webview_count = 0;

}
